import axios from 'axios'
import store from '@/store'
import router from '@/router'
import to from 'await-to-js'
import errorCode from '@/utils/errorCode'
import { Toast } from 'vant'

// 新axios实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  err => {
    Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode.default
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      Toast('无效的会话，或者会话已过期，请重新登录。')
      store.commit('user/setToken', '')
      router.push('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
    } else if (code === 500) {
      Toast.fail(msg)
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      Toast.fail(msg)
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Toast(message)
    if (error.response && error.response.status === 401) {
    // token失效
      store.commit('user/setToken', '')
      router.push('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    return Promise.reject(error)
  }
)

// 导出一个新axios实例调用接口的函数，返回值promise
export default ({ url, method = 'get', params, data, headers }) => {
  const promise = instance({ url, method, params, data, headers })
  return to(promise)
}
